package cn.jhc.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;

import cn.jhc.bean.UserBean;
import cn.jhc.dao.ConnectionFactory;
import cn.jhc.dao.TitleDAO;

@WebServlet("/download.do")
public class DownloadServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		HttpSession session = request.getSession();
		UserBean user = (UserBean) session.getAttribute("user");
		if (null == user) {
			String getb = (String) request.getParameter("getb");
			String id = (String) request.getParameter("id");
			request.setAttribute("id", id);
			request.setAttribute("getb", getb);
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("/login.jsp");
			dispatcher.forward(request, response);
			return;
		} else {
			Connection conn = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			String realPath = request.getSession().getServletContext()
					.getRealPath("/");

			String integral = request.getParameter("integral");
			int Integral = Integer.parseInt(integral);
			String need_integral = request.getParameter("need_integral");
			int Need_integral = Integer.parseInt(need_integral);
			if ((Integral - Need_integral) < 0) {
				RequestDispatcher dispatcher = request
						.getRequestDispatcher("/yuepudownload2.jsp");
				dispatcher.forward(request, response);
				return;
			} else {
				String imagename = request.getParameter("imagename");
				if (null == imagename || imagename.equals("")) {
					return;
				}

				File file = null;

				InputStream is = null;
				String fileName = null;
				int fileSize = 0;

				file = new File(realPath + "UserFiles/Image/" + imagename);
				is = new FileInputStream(file);
				fileName = file.getName();
				fileSize = (int) file.length();

				response.setContentType("application/x-msdownload");
				String str = "attachment; filename="
						+ encodeFilename(fileName, request);
				response.setHeader("Content-Disposition", str);
				response.setContentLength(fileSize);

				ServletOutputStream sos = response.getOutputStream();
				byte[] data = new byte[2048];
				int len = 0;
				while ((len = is.read(data)) > 0) {
					sos.write(data, 0, len);
				}
				is.close();
				sos.close();
			}
			int the_integral = Integral-Need_integral;
			TitleDAO dao = new TitleDAO();
			int userid = user.getId();
			dao.setCon(ConnectionFactory.getConnection());
			dao.MinusIntegral(the_integral, userid);
		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	public String encodeFilename(String fileName, HttpServletRequest request) {
		HttpServletRequest req = new HttpServletRequestWrapper(request);
		String agent = req.getHeader("USER-AGENT");
		try {
			// IE
			if (null != agent && -1 != agent.indexOf("MSIE")) {
				fileName = URLEncoder.encode(fileName, "UTF8");
				// Firefox
			} else if (null != agent && -1 != agent.indexOf("Mozilla")) {
				fileName = MimeUtility.encodeText(fileName, "UTF8", "B");
			}
		} catch (UnsupportedEncodingException e) {
			try {
				fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
		return fileName;
	}

}
